<template>
  <div>
    <h2>房型增加</h2>
    <table class="table table-bordered">
      <tr>
        <td align="right">房型名称</td>
        <td>
          <input type="text"  v-model="state.hTypeName"/>
        </td>
      </tr>
      <tr>
        <td align="right">房型图片</td>
        <td>
          <input type="file" @change="change" />
          <img :src="src" width="60" height="60" alt="" v-if="src != ''" />
        </td>
      </tr>
      <tr>
        <td align="right">面积</td>
        <td>
          <input type="text" v-model="state.hTypeArea" />m
        </td>
      </tr>
      <tr>
        <td align="right">入住人数</td>
        <td>
          <input type="text" v-model="state.hTypeNumber" />人
        </td>
      </tr>
      <tr>
        <td align="right"></td>
        <td>
          <input type="button" value="增加" @click="ok" />
        </td>
      </tr>
    </table>
  </div>
</template>

<script setup lang="ts">
import { reactive, toRefs, onMounted } from 'vue';
import axios from 'axios';
import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();

let data = reactive({
  src: '',
  state: {
    hTypeName: '',
    hTypePhoto: '',
    hTypeNumber: '',
    hTypeArea: '',
  }
});

let { src,state } = toRefs(data);

//函数
const ok = ()=>{
  //1.非空+有效
  //2.发送请求
  let obj = {
    hTypeName: state.value.hTypeName,
    hTypePhoto: state.value.hTypePhoto,
    hTypeNumber: state.value.hTypeNumber,
    hTypeArea: state.value.hTypeArea,
  }
  axios({
    url:'/api/Test/PostAddHouseType',
    method:'post',
    data:obj
  })
  .then(res=>{
    console.log(res);
    if(res.data.data == 1){
      alert("添加成功");
      router.push("houseTypeList")
    }else if(res.data.data == -1){
      alert("房型重复");
      return
    }else{
      alert("添加失败");
      return
    }

    
  }).catch(err=>{
    console.log(err);
    
  })
}


//上传图片
const change = (e: any) => {
  console.log(e);
  let formData = new FormData();
  let obj = e.target.files[0];
  formData.append('file', obj);

  axios({
    url: '/api/Test/PostUploadImgs',
    method: 'post',
    data: formData
  })
    .then((res) => {
      console.log(res);
      if (res.data.code == 1002) {
        alert(res.data.msg);
        return;
      }
      if (res.data.code == 1001) {
        alert(res.data.msg);
        return;
      }
      src.value = 'https://localhost:7086' + res.data.data;
      state.value.hTypePhoto = res.data.data

    })
    .catch((err) => {
      console.log(err);
    });
};
</script>

<style scoped></style>
